import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { SingerItem } from '@/views/singer/index.vue'

const FIX_TITLE_HEIGHT = 30 // 固定头的高度
export default (props: Readonly<{ singers: SingerItem[] }>) => {
    const wrapper = ref<HTMLElement | null>(null) // singer-group元素实例
    const currentIndex = ref<number>(0) // 当前选中的索引
    const positionArray = ref<number[]>([]) // 元素距离底部的高度的数组
    const fixedWrapper = ref<HTMLElement | null>(null) // 固定标题元素

    const fixTitle = computed(() => (
        props.singers[currentIndex.value] ? props.singers[currentIndex.value].title : ''
    ))
    // 监听props.singers, 因为不知道什么时候将singers的值传进来，所以要监听，当监听到singers的值发生改变时，然后调用nextTick，当页面渲染之后再重新计算高度
    watch(() => props.singers, async () => {
        await nextTick()
        if (wrapper.value !== null) {
            positionArray.value = [0]
            Array.from(wrapper.value.children).forEach((element, index) => {
                const height = (element as HTMLElement).offsetHeight
                positionArray.value.push(height + positionArray.value[index])
            })
        }
    })
    const scroll = ({ y }: {x: number, y: number}) => {
       const pa = positionArray.value
       for (let i = 0; i < pa.length - 1; i++) {
            if (-y >= pa[i] && -y < pa[i + 1]) {
                currentIndex.value = i
                if (pa[i + 1] - (-y) < FIX_TITLE_HEIGHT) {
                    const moveY = FIX_TITLE_HEIGHT - (pa[i + 1] - (-y))
                    if (fixedWrapper.value !== null) {
                        fixedWrapper.value.style.transform = `translateY(-${moveY}px) translateZ(2px)`
                    }
                } else {
                    if (fixedWrapper.value !== null) {
                        fixedWrapper.value.style.transform = 'translateY(0px) translateZ(2px)'
                    }
                }
                break
            } else {
                currentIndex.value = -1
            }
       }
    }
    return {
        wrapper,
        currentIndex,
        scroll,
        fixTitle,
        fixedWrapper
    }
}
